<template>
  <el-row>
    <el-col :span="24">
      <div>
        <el-form ref="queryForm" :model="queryParams" :inline="true" size="medium" @submit.prevent.native>
          <el-form-item :label="$t('指标名称')" prop="keyName">
            <el-input
              v-model="queryParams.keyName"
              :placeholder="$t('指标名称')"
              clearable
              :onsubmit="false"
              @keyup.enter.native="queryHandle"
            />
          </el-form-item>
          <el-form-item :label="$t('关注指标')" prop="focusOn">
            <!-- <el-select v-model="queryParams.focusOn" :placeholder="$t('关注指标')" clearable>
              <el-option
                v-for="item in focusOnOptions"
                :key="item.keyCode"
                :label="item.keyName"
                :value="item.keyName"
              />
            </el-select> -->
            <el-radio-group v-model="focusKeys" size="mini" @input="focusName">
              <el-radio-button label="全部" />
              <el-radio-button label="关注" />
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
          </el-form-item>
        </el-form>
        <el-table
          ref="scrollTable"
          :data="tableData"
          row-key="id"
          max-height="593"
          height="593"
          default-expand-all
          border
        >
          <el-table-column :label="$t('分类')" width="160" align="left" prop="keyReport" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.pid === '0'">{{ $t(scope.row.keyReport) }}</span>
              <el-input v-if="!scope.row.id" v-model="scope.row.keyReport" :placeholder="$t('分类')" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('指标名称')" align="center" prop="keyName">
            <template slot-scope="scope">
              <!-- <el-select v-if="scope.row.pid !== '0'" v-model="scope.row.keyName" placeholder="请选择" style="width:100%">
                <el-option
                  v-for="item in dataKeysByReport[scope.row.keyReport][0].children"
                  :key="item.id"
                  :label="item.keyName"
                  :value="item.keyCode"
                />
              </el-select> -->
              <el-autocomplete
                v-if="scope.row.pid !== '0'"
                v-model="scope.row.keyName"
                disabled
                :fetch-suggestions="querySearch"
                show-word-limit
                style="width: 100%"
                :maxlength="100"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column :label="$t('公式')" align="right" prop="indicatorsFormula">
            <template slot-scope="scope">
              <div class="overflowText">
                <span v-if="scope.row.pid !== '0'" :title="formatGS(scope.row)" v-text="formatGS(scope.row)" />
              </div>
            </template>
          </el-table-column> -->
          <el-table-column :label="$t('值')" width="300" align="center" prop="keyValue">
            <template slot-scope="scope">
              <!-- <el-input-number v-if="scope.row.pid !== '0'" v-model="scope.row.keyValue" type="number" controls-position="right" :max="999999999" /> -->
              <money v-if="scope.row.pid !== '0'" v-model="scope.row.keyValue" decimal-places="4" />
            </template>
          </el-table-column>
          <!-- <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="120">
            <template slot-scope="scope">
              <div v-if="scope.row.pid !== '0'">
                <el-button size="medium" type="text" icon="el-icon-plus" @click="addHandle(scope.row,scope.$index)" />
                <el-button size="medium" type="text" icon="el-icon-delete" @click="deleteHandle(scope.row,scope.$index)" />
              </div>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <div style="width:100%;height:70px" />
    </el-col>
  </el-row>
</template>

<script>
import {
   findTempDataKeysByCompanyId,
   findFocusOnKeys
} from '@/api/company/pcw/pcwTempSubject'

export default {
  name: 'HandEnter',
  props: {
    companyId: {
      type: String,
      required: true
    },
    isAdd: {
      type: Boolean,
      required: true
    },
    sheetData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      tableData: [],
      tempSubject: [], // 模板科目
      tempSubjectName: [], // 模板科目名字相似度用到的
      enableCopyExcel: false,
      matchingRatio: 0, // 已匹配科目百分比
      matchingStatusRatio: {
        success: 0,
        warning: 0,
        danger: 0
      },
      clipboard: '',
      selectedCell: null,
      dataKeysOption: [],
      childrenArray: [],
      queryParams: {
        keyName: '',
        focusOn: ''
      },
      focusOnOptions: [],
      cacheTable: [],
      focusKeys: '全部'
    }
  },
  watch: {
    // tableData: {
    //   immediate: true,
    //   handler() {
    //     this.$nextTick(() => {
    //       this.scrollToBottom()
    //     })
    //   }
    // }
  },
  mounted() {
    //  this.initAddSubject()
    console.log('this.sheetData', this.sheetData)
  },
  created() {
      if (this.isAdd) {
        const keyName = this.queryParams.keyName
        const focusOn = this.queryParams.focusOn
            findTempDataKeysByCompanyId(this.companyId, keyName, focusOn).then(res => {
              this.tableData = res.data
              this.cacheTable = this.tableData
              if (this.tableData.length > 0) {
                const childrenArray = this.extractChildren(this.tableData)
                this.childrenArray = childrenArray.map(item => {
                    return {
                      'value': item.keyName
                    }
                })
              }
        })
      }
      // 查询关注关键指标
      findFocusOnKeys(this.companyId).then(res => {
      // this.focusOnOptions = res.data
       const keyNameValues = res.data.map((option) => option.keyName)
       this.focusOnOptions = keyNameValues
       this.loading = false
    })
  },
  methods: {
    init() {
      this.tableData = this.sheetData
      this.cacheTable = this.sheetData
    },
    scrollToBottom() {
      const tableBody = this.$refs.scrollTable.$el.querySelector('.el-table__body-wrapper')
      tableBody.scrollTop = tableBody.scrollHeight - tableBody.clientHeight
    },
    deleteHandle(row, index) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        }).then(function() {
          return true
        }).then(() => {
          // delDataBaseById(row.id)
          this.tableData.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {})
      } else {
        this.tableData.splice(index, 1)
        // return this.msgSuccess(this.$t('删除成功'))
      }
    },
    querySearch(queryString, cb) {
      // 对应模板的科目列表
      var restaurants = this.childrenArray
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    addHandle(row, index) {
       const rowObj = row
       rowObj.keyName = undefined
       this.tableData.splice(index, 0, rowObj)
    },
   extractChildren(data) {
            return data.reduce((acc, item) => {
          if (item.children) {
            acc.push(...this.extractChildren(item.children))
          } else {
            acc.push(item)
          }
          return acc
        }, [])
    },
    queryHandle() {
        this.tableData = this.cacheTable
        if (this.queryParams.keyName === '') {
          return
        }
        const keyName = this.queryParams.keyName
        const filteredTableData = this.filterTreeDataStr(this.tableData, 'keyName', keyName)
        this.tableData = filteredTableData
        // findTempDataKeysByCompanyId(this.companyId, keyName, focusOn).then(res => {
        //     this.tableData = res.data
        // })
    },
    resetQuery() {
      this.queryParams = {
        keyName: '',
        focusOn: ''
      }
      this.tableData = this.cacheTable
    },
     filterTreeData(data, keyName, searchValue) {
        const filteredData = []
        data.forEach((item) => {
          if (item[keyName] && searchValue.includes(item[keyName])) {
            filteredData.push(item)
          }
          if (item.children && item.children.length > 0) {
            const filteredChildren = this.filterTreeData(item.children, keyName, searchValue)
            if (filteredChildren.length > 0) {
              filteredData.push({
                ...item,
                children: filteredChildren
              })
            }
          }
        })
        return filteredData
      },
       filterTreeDataStr(data, keyName, searchValue) {
        const filteredData = []
        data.forEach((item) => {
          if (item[keyName] && item[keyName].indexOf(searchValue) !== -1) {
            filteredData.push(item)
          }
          if (item.children && item.children.length > 0) {
            const filteredChildren = this.filterTreeDataStr(item.children, keyName, searchValue)
            if (filteredChildren.length > 0) {
              filteredData.push({
                ...item,
                children: filteredChildren
              })
            }
          }
        })
        return filteredData
      },
      focusName(name) {
         if (name === '关注') {
              const filteredTableData = this.filterTreeData(this.cacheTable, 'keyName', this.focusOnOptions)
              this.tableData = filteredTableData
         } else {
            // 展示全部
            this.tableData = this.cacheTable
         }
      }
  }
}
</script>

<style scoped>
.small-tag {
  margin-right: 10px;
  height: 18px;
  line-height: 16px;
  padding: 0px 2px;
  font-size: 5px;
  width: 18px;
}

.tag_contain {
  margin: 24px 0px;
}

.bottom_contain {
  display: flex;
  justify-content: space-between;
}
</style>
